package com.pureman.androidapp;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.pureman.androidapp.network.NetWorkBroadcastReceiver;
import com.pureman.androidapp.network.NetWorkUtil;
import com.pureman.androidapp.socket.ConnectConfig;
import com.pureman.androidapp.utils.LogUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class BaseStationModeActivity extends BaseActivity implements NetWorkBroadcastReceiver.NetWorkEventHandler {

    private ExecutorService cachedThreadPool;

    private AlertDialog connDialog;

    private Dialog loadDialog;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stereoview_activity_main);

        LogUtils.i("BaseStationModeActivity-->onCreate");

        loadDialog = createLoadingDialog(this, "");
        loadDialog.show();

        cachedThreadPool = Executors.newCachedThreadPool();
//        cachedThreadPool = Executors.newFixedThreadPool(3);

        if (NetWorkUtil.getNetworkState(this) == NetWorkUtil.NETWORN_NONE) {
            showDialog();
        }

        scheduledThreadPool = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
//                LogUtils.i("BaseStationModeActivity-->scheduleAtFixedRate");
                if (reconnect) {
                    connectSocket();
                }
            }
        }, 1, 5, TimeUnit.SECONDS);
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.i("BaseStationModeActivity-->onResume");
        reconnect = true;
        NetWorkBroadcastReceiver.mListeners.add(this);
    }


    @Override
    public void onPause() {
        super.onPause();
        LogUtils.i("BaseStationModeActivity-->onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.i("BaseStationModeActivity-->onStop");
        reconnect = false;
        NetWorkBroadcastReceiver.mListeners.remove(this);
    }

    @Override
    protected void onDestroy() {
        LogUtils.i("BaseStationModeActivity-->onDestroy");
        if (scheduledThreadPool != null) {
            scheduledThreadPool.shutdown();
        }
        if (cachedThreadPool.isShutdown()) {
            cachedThreadPool.shutdown();
        }
        super.onDestroy();
    }

    @Override
    public void onNetWorkChange() {
        LogUtils.i("BaseStationModeActivity-->onNetWorkChange");
        if (NetWorkUtil.getNetworkState(this) == NetWorkUtil.NETWORN_NONE) {
            showDialog();
        }
    }

    private void showDialog() {
        if (connDialog == null) {
            connDialog = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher)
                    .setTitle(getString(R.string.not_connect)).setPositiveButton(
                            getString(R.string.ok),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                }
                            }).create();
        }
        if (!connDialog.isShowing()) {
            connDialog.show();
        }
    }

    /**
     * 得到自定义的progressDialog
     *
     * @param context
     * @param msg
     * @return
     */
    private Dialog createLoadingDialog(Context context, String msg) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.loading_dialog, null);// 得到加载view
        RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.dialog_view);// 加载布局
        // main.xml中的ImageView
        ProgressBar spaceshipImage = (ProgressBar) v.findViewById(R.id.progressBar);
//        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
//        // 加载动画
//        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
//                context, R.anim.load_animation);
//        // 使用ImageView显示动画
//        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
//        tipTextView.setText(msg);// 设置加载信息

        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog

        loadingDialog.setCancelable(false);// 不可以用“返回键”取消
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
        return loadingDialog;
    }

    //    private static final String HOST = "192.168.1.255";
    private static final String HOST = "255.255.255.255";

    private ScheduledExecutorService scheduledThreadPool;

    private boolean reconnect = false;

    private void connectSocket() {
        try {
            // 创建发送方的套接字 对象 采用9004默认端口号
            DatagramSocket socket = new DatagramSocket();
            socket.setSoTimeout(ConnectConfig.TIME_OUT);

            // 发送的内容
//            String text = "hi 红军!";
//            byte[] buf = text.getBytes();
            byte[] buf = ConnectConfig.WIFI_SEND_INIT;
            // 构造数据报包，用来将长度为 length 的包发送到指定主机上的指定端口号。
            DatagramPacket packet = new DatagramPacket(buf, buf.length,
                    InetAddress.getByName(HOST), ConnectConfig.PORT);

            // 从此套接字发送数据报包
            socket.send(packet);

            // 接收，接收者返回的数据
            displayReciveInfo(socket);

            // 关闭此数据报套接字。
            socket.close();
        } catch (SocketException e) {
            e.printStackTrace();
            LogUtils.i("UDP SocketException-->" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.i("UD IOException-->" + e.getMessage());
        } finally {
            if (loadDialog != null && loadDialog.isShowing()) {
                loadDialog.dismiss();
            }
        }
    }

    /**
     * 接收数据并打印出来
     *
     * @param socket
     * @throws IOException
     */
    private void displayReciveInfo(DatagramSocket socket)
            throws IOException {
        byte[] buffer = new byte[128];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        socket.receive(packet);

        byte data[] = packet.getData();// 接收的数据
        InetAddress address = packet.getAddress();// 接收的地址
//        LogUtils.i("接收的文本: " + new String(data));
//        LogUtils.i("接收的ip地址: " + address.toString());
//        LogUtils.i("接收的端口: " + packet.getPort()); // 9004
        LogUtils.i("接收的主机名1: " + address.getHostName()); // 9004
//        LogUtils.i("接收的主机名2: " + address.getHostAddress()); // 9004
//        LogUtils.i("接收的主机名3: " + new String(address.getAddress(), "ISO-8859-1").trim()); // 9004

        SocketAddress socketAddress = packet.getSocketAddress();
//        LogUtils.i("接收的主机名4: " + socketAddress.toString());

        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }

    class LoadTask extends AsyncTask<Integer, Void, Void> {
        @Override
        protected Void doInBackground(Integer... params) {
            try {
                Thread.sleep(1000);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
                System.out.println("targetSdkVersion == " + getTargetSdkVersion() + " LoadTask#" + params[0] + " time == " + df.format(new Date()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
    }

    private String getTargetSdkVersion() {
        int targetSdkVersion = 0;
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            targetSdkVersion = packageInfo.applicationInfo.targetSdkVersion;
        } catch (PackageManager.NameNotFoundException e) {
        }

        return targetSdkVersion + "";
    }

    private void taskTest() {
        for (int index = 0; index < 10; index++) {
            new LoadTask().execute(index);
        }
    }
}